<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  classList as classPage,
  insertClass,
  updateClass,
  deleteClass
} from '@/api/class'

const pageNo   = ref(1)
const total    = ref(0)
const pageSize = ref(5)

const searchName = ref('')

const tableData = ref([])

const drawerVisible = ref(false)
const isEdit = ref(false)
const formModel = ref({
  id: '',
  name: '',
  description: '',
  parentid: 0,
  coverimage: '',
  sortorder: 0,
  isfeatured: 0
})

const resetObj = obj => Object.keys(obj).forEach(k => (obj[k] = ''))

onMounted(() => loadList())

const loadList = () => {
  const params = {
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    name: searchName.value
  }
  classPage(params).then(res => {
    if (res.success) {
      total.value   = res.data.count
      tableData.value = res.data.records || []
    }
  })
}

const handleSearch = () => {
  pageNo.value = 1
  loadList()
}
const resetSearch = () => {
  searchName.value = ''
  handleSearch()
}

const openAdd = () => {
  isEdit.value = false
  resetObj(formModel.value)
  formModel.value.parentid = 0
  formModel.value.sortorder = 0
  formModel.value.isfeatured = 0
  drawerVisible.value = true
}
const openEdit = row => {
  isEdit.value = true
  Object.assign(formModel.value, row)
  drawerVisible.value = true
}

const handleDelete = id => {
  ElMessageBox.confirm('确认删除该分类？', '提示', { type: 'warning' })
    .then(() => deleteClass({ id }))
    .then(res => {
      ElMessage.success(res.message || '删除成功')
      loadList()
    })
}

const handleSubmit = () => {
  const api = isEdit.value ? updateClass : insertClass
  api(formModel.value).then(res => {
    if (res.success) {
      ElMessage.success(res.message || '操作成功')
      drawerVisible.value = false
      loadList()
    }
  })
}

const handleAvatarSuccess = res => (formModel.value.coverimage = res.message)
const beforeAvatarUpload = rawFile => {
  if (!rawFile.type.startsWith('image/')) {
    ElMessage.error('请上传图片')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能大于 2MB')
    return false
  }
  return true
}

const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  sortorder: [
    { required: true, message: '请输入排序权重', trigger: 'blur' },
    { type: 'number', min: 0, message: '必须为非负整数', trigger: 'blur' }
  ]
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>分类管理</span>
        <el-button type="primary" :icon="Plus" @click="openAdd">新增分类</el-button>
      </div>
    </template>

    <el-form inline>
      <el-form-item label="分类名称">
        <el-input v-model="searchName" placeholder="请输入名称" clearable @keyup.enter="handleSearch" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%" stripe>
      <el-table-column label="ID" prop="id" width="60" />
      <el-table-column label="名称" prop="name" width="120" />
      <el-table-column label="排序权重" prop="sortorder" width="100" />
      <el-table-column label="描述" prop="description" show-overflow-tooltip />
      <el-table-column label="首页展示" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isfeatured ? 'success' : 'info'">
            {{ row.isfeatured ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" prop="createdtime" width="160" />
      <el-table-column label="更新时间" prop="updatedtime" width="160" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button :icon="Edit" circle type="primary" @click="openEdit(row)" />
          <el-button :icon="Delete" circle type="danger" @click="handleDelete(row.id)" />
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </el-table>

    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="val => { pageSize = val; pageNo = 1; loadList() }"
      @current-change="val => { pageNo = val; loadList() }"
      style="margin-top: 20px; justify-content: flex-end"
    />

    <el-drawer
      v-model="drawerVisible"
      :title="isEdit ? '编辑分类' : '新增分类'"
      direction="rtl"
      size="480"
    >
      <el-form ref="formRef" :model="formModel" :rules="rules" label-position="top">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formModel.name" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input v-model="formModel.description" type="textarea" :rows="3" />
        </el-form-item>

        <el-form-item label="排序权重" prop="sortorder">
          <el-input-number v-model="formModel.sortorder" :min="0" />
        </el-form-item>

        <el-form-item label="首页展示" prop="isfeatured">
          <el-switch v-model="formModel.isfeatured" :active-value="1" :inactive-value="0" />
        </el-form-item>

        <el-form-item label="父级ID" prop="parentid">
          <el-input-number v-model="formModel.parentid" :min="0" />
        </el-form-item>


      </el-form>

      <template #footer>
        <div style="text-align: right">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>

<style scoped>
:root {
  --macaron-pink: #ff9db0;
  --macaron-mint: #a5e6ba;
  --macaron-blue: #8fd3f4;
  --macaron-yellow: #ffe66d;
  --macaron-purple: #d9b8ff;
  --macaron-bg: #fafafa;
  --macaron-card: #ffffff;
}

.page-container {
  min-height: 100%;
  box-sizing: border-box;
  background: linear-gradient(135deg, var(--macaron-bg), #f0f9ff);
  padding: 24px;
  border-radius: 20px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.header span {
  font-size: 22px;
  font-weight: 700;
  color: var(--macaron-blue);
}

.el-button--primary {
  background: var(--macaron-pink);
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(255, 157, 176, 0.3);
}

.el-table {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.el-table th {
  background: var(--macaron-mint) !important;
  color: #fff;
  font-weight: 600;
}

.el-tag--success {
  background: var(--macaron-yellow);
  color: #5c3c00;
}

.el-pagination {
  margin-top: 24px;
  justify-content: center;
}

.el-drawer {
  border-radius: 24px 0 0 24px;
}

.el-form-item__label {
  font-weight: 600;
  color: var(--macaron-blue);
}

.el-input,
.el-textarea,
.el-input-number {
  border-radius: 12px;
}

.avatar-uploader .avatar {
  width: 160px;
  height: 160px;
  border-radius: 16px;
  object-fit: cover;
}

.el-table {
  font-size: 16px;          /* 内容字号 */
  line-height: 1.6;
}
.el-table th {
  font-size: 17px;          /* 表头字号 */
  font-weight: 700;
}
.el-table .cell {
  padding: 12px 8px;        /* 增加内边距，防止拥挤 */
}

.avatar-uploader-icon {
  font-size: 48px;
  color: var(--macaron-purple);
}
</style>